package cn.kgc.service.impl;

import cn.kgc.constant.MessageInfoType;
import cn.kgc.entity.Messageinfo;
import cn.kgc.mapper.MessageinfoMapper;
import cn.kgc.service.ConsumerMessageInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wangyue
 * @version 1.0
 */
@Service("consumerMessageInfoService")
public class ConsumerMessageInfoServiceImpl implements ConsumerMessageInfoService {

    @Resource
    private MessageinfoMapper messageinfoMapper;

    @Override
    public void messageReceiveDead(String id) {
        //根据id获得消息
        Messageinfo messageinfo = messageinfoMapper.selectById(id);
        if(messageinfo!=null){
            messageinfo.setType("receive:"+ MessageInfoType.DEAD.getType());
            //更新消息
            messageinfoMapper.updateById(messageinfo);
        }
    }

    @Override
    public void messageReceiveSuccess(String id) {
        messageinfoMapper.deleteById(id);
    }

    @Override
    public Messageinfo messageReceiveReady(String id, String exchange, String routingKey,
                                           String queue, String body,long delayTime) {
        //1 根据消息的id判断消息是否存在,如果不存在则新增消息。
        Messageinfo messageinfo = messageinfoMapper.selectById(id);
        if(messageinfo==null){
            messageinfo=new Messageinfo();
            messageinfo.setId(id);
            messageinfo.setExchange(exchange);
            messageinfo.setRoutingkey(routingKey);
            messageinfo.setQueue(queue);
            messageinfo.setPayload(body);
            //消息的类型是RECEIVE状态
            messageinfo.setType(MessageInfoType.RECEIVE.getType());
            //消息的处理次数
            messageinfo.setSequence(1);
            //消息的延迟时间
            messageinfo.setDelaytime(delayTime);
            //保存消息
            messageinfoMapper.insert(messageinfo);
        }else{
            //2 如果消息存在,修改消息消费的次数+1
            messageinfo.setSequence(messageinfo.getSequence()+1);
            messageinfoMapper.updateById(messageinfo);
        }
        return messageinfo;
    }
}
